package com.jblv.frame.user.service.config;

import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.ResourcePropertySource;

import java.io.IOException;

public class CustomEnvironment extends StandardEnvironment {

    private static final String APPCONFIG_PATH_PATTERN = "classpath:application-%s.properties";

    @Override
    protected void customizePropertySources(MutablePropertySources propertySources) {
        super.customizePropertySources(propertySources);
        try {
            propertySources.addLast(initResourcePropertySourceLocator());
        } catch (IOException e) {
            logger.warn("failed to initialize application config environment", e);
        }
    }

    private PropertySource<?> initResourcePropertySourceLocator() throws IOException {
        String profile = System.getProperty("spring.profiles.active", "dev");
        String configPath = String.format(APPCONFIG_PATH_PATTERN, profile);
        System.out.println("Using application config: " + configPath);

        Resource resource = new DefaultResourceLoader(this.getClass().getClassLoader()).
                getResource(configPath);
        PropertySource resourcePropertySource = new ResourcePropertySource(resource);
        return resourcePropertySource;
    }
}